import { useRef } from "react"

export type noop = (...args: any[]) => any

/**
 * 持久化 function 的 Hook。
 * @param fn 需要持久化的函数
 */
function usePersistFn<T extends noop>(fn: T) {
  const fnRef = useRef<T>(fn)
  fnRef.current = fn

  const persistFn = useRef<T>()
  if (!persistFn.current) {
    // eslint-disable-next-line func-names
    persistFn.current = function (...args) {
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      return fnRef.current!.apply(this, args)
    } as T
  }

  return persistFn.current!
}

export default usePersistFn
